package com.lill.system.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

//@Component("shiroSessionFilter")
public class ShiroSessionFilter implements Filter {
	
	public List<String> excludes = new ArrayList<String>();
	
	private long serverSessionTimeout = 360000L;//ms

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if(handleExcludeURL(request, response)){
        	if(request.getServletPath().contains("ueditor/jsp/controller.jsp")){
        		request.getRequestDispatcher("/sys/ueditor/config").forward(request, response);
        		return;
        	}
            chain.doFilter(req, res);
            return;
        }
        
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()){
        	currentUser.getSession().setTimeout(serverSessionTimeout);
        }
        chain.doFilter(req, res);
	}

	
	private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }

        String url = request.getServletPath();
        for (String pattern : excludes) {
        	if(Pattern.compile("^"+pattern).matcher(url).find()){
        		return true;
        	}
        }
        return false;
    }

	public void init(FilterConfig filterConfig) throws ServletException {
        excludes.add("/statics/*");
        excludes.add("/");
        excludes.add("/favicon.ico");
        serverSessionTimeout=3600000L;
	}


	@Override
	public void destroy() {
		
	}
}
